﻿using MediatR;
using RedDragon.Common.Domain.AuthorizeRBAC;
using RedDragon.Common.Dtos;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.RBAC.ErrorCodeEnum;
using SqlSugar;
using T.Common.Domain.Common;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
namespace RedDragon.RBAC.API.Application.Common.Permission
{
    public class QueryPermissionsHandler : IRequestHandler<QueryPermissionsCommand, Result<PageResultDto<PermissionsDto>>>
    {
        private readonly ISqlSugarClient _db;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreatePermissionsHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="logger"></param>
        public QueryPermissionsHandler(
            ISqlSugarClient db,
            ILogger<CreatePermissionsHandler> logger)
        {
            _db = db;
            this.logger = logger;
        }
        /// <summary>
        /// 权限分类列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<PermissionsDto>>> Handle(QueryPermissionsCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<PermissionsDto>>() { Code = (int)CommonErrorCode.Search };
            //实例化分页种母期初
            var page = new PageResultDto<PermissionsDto>() { TotalCount = 0, PageCount = 0, List = new List<PermissionsDto>() };
            try
            {    
                //总条数
                RefAsync<int> totalCount = 0;
                //总页数
                RefAsync<int> totalPage = 0;
                var query = _db.Queryable<Permissions, PermissionTypes>((p, t) => p.PermissionTypeId == t.PermissionTypeId)
                    .Select((p, t) => new PermissionsDto()
                    {
                        PermissionId = p.PermissionId,
                        PermissionCoding = p.PermissionCoding,
                        PermissionState = p.PermissionState,
                        IsDelete = p.IsDelete,
                        URL = p.URL,
                        PermissionTypeId = p.PermissionTypeId,
                        PermissionName = p.PermissionName,
                        CreatedOwner = p.CreatedOwner,
                        CreatedTime = p.CreatedTime,
                        PermissionTypeName = t.PermissionTypeName,
                    }).Where(p=>p.IsDelete==0);
                //权限编号模糊查
                if (!string.IsNullOrEmpty(request.PermissionCoding))
                {
                    query = query.Where(p => p.PermissionCoding.Contains(request.PermissionCoding));
                }
                //权限名称模糊查
                if (!string.IsNullOrEmpty(request.PermissionName))
                {
                    query = query.Where(p => p.PermissionName.Contains(request.PermissionName));
                }
                //权限分类ID查询
                if (request.PermissionTypeId > 0)
                {
                    query = query.Where(p => p.PermissionTypeId == request.PermissionTypeId);
                }
                //状态查询
                if (request.PermissionState > 0)
                {
                    query = query.Where(p => p.PermissionState == request.PermissionState);
                }
                // 执行分页查询，并获取总条数和总页数
                var list = await query.ToPageListAsync(request.PageIndex, request.PageSize, totalCount, totalPage);
                //总条数
                page.TotalCount = totalCount;
                //总页数
                page.PageCount = totalPage;
                //跳过多少条 每页显示几条 
                page.List = list;
                // 如果查询结果不为空，则设置返回结果为成功，并附带分页信息和消息
                if (page.List.Any())
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = page;
                    result.Msg = "获取权限列表成功";
                }
            }
            catch (Exception ex)
            {
                logger.LogError("获取权限数据异常" + ex.Message);
                result.Msg = "获取权限数据异常" + ex.Message;
            }
            return result;
        }
    }
}
